//
//  YKSearchViewController.m
//  YunKang
//
//  Created by leoking870 on 2017/11/8.
//  Copyright © 2017年 leoking870. All rights reserved.
//

#import "YKSearchViewController.h"
#import "YKDropdown.h"
#import "YKPopupView.h"
@interface YKSearchViewController ()<UISearchBarDelegate>
@property (nonatomic, strong)NSArray *filterredDataSource;
@end

@implementation YKSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UISearchBar *searchBar = [[UISearchBar alloc]init];
    searchBar.placeholder = @"查询关键字";
    searchBar.delegate = self;
    [self.view addSubview:searchBar];
    [searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.trailing.equalTo(self.view);
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.bottom.trailing.equalTo(self.view);
        make.top.equalTo(searchBar.mas_bottom);
    }];
    self.filterredDataSource = self.dataSource;
    [self updateViews];
}

- (void)updateViews {
    [self.tableViewManager removeAllSections];
    TFTableViewSection *section = [TFTableViewSection section];
    section.headerHeight = .1f;
    section.footerHeight = .1f;
    @weakify(self)
    for (id<YKDropdown> model in self.filterredDataSource) {
        TFTitleDetailItem *item = [TFTitleDetailItem itemWithTitle:model.name detail:nil];
        item.model = model;
        item.selectionHandler = ^(__kindof TFTitleDetailItem *item, NSIndexPath *indexPath) {
            if (self_weak_.selectHandler) {
                self_weak_.selectHandler(item.model);
            }
            [YKPopupView dismissViewController:self_weak_];
        };
        if ([self.currentSelectModel.id_p isEqual:model.id_p]) {
            item.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else {
            item.accessoryType = UITableViewCellAccessoryNone;
        }
        [section addItem:item];
    }
    [self.tableViewManager addSection:section];
    
    [self.tableView reloadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    [self updateTableViewByText:searchText];
}

- (void)updateTableViewByText:(NSString *)name{
    if (name.length == 0) {
        self.filterredDataSource = self.dataSource;
    }
    else {
        self.filterredDataSource = [self.dataSource tf_filteredWithPredicateBlock:^BOOL(id  _Nonnull obj, NSInteger idx) {
            id<YKDropdown> model = obj;
            if ([model.name containsString:name]) {
                return YES;
            }
            return NO;
        }];
    }
    [self updateViews];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [self updateTableViewByText:searchBar.text];
}

@end
